//
//  UserAccountViewModel.swift
//  SinaWeibo
//
//  Created by 李旭阳 on 15/11/10.
//  Copyright © 2015年 apple. All rights reserved.
//

import UIKit
import AFNetworking

//ViewModel 将一些业务逻辑封装到 这个类里  让这个隔离的更加好
class UserAccountViewModel: NSObject {
    
    //增加userAccount 属性
    var account: UserAccount?
    
    //MARK: 在init方法中获取 用户账户
    override init() {
        account = UserAccount.loadAccount()
    }
    
    //MARK: 用户是否登录
    var userLogin: Bool{
        return account?.access_token != nil
    }
    
    //MARK: 增加 token 属性
    var token: String? {
        return account?.access_token
    }
    
    //MARK:  获取token
    func loadAccessToKen(code: String,finished: (error: NSError?) -> ()){
        
        let urlSting = "https://api.weibo.com/oauth2/access_token"
        let parameters =  ["client_id": client_id,"client_secret":client_secret,"grant_type" : "authorization_code","code":code,"redirect_uri":redirect_uri]
        
        let AFN = AFHTTPSessionManager()
        AFN.responseSerializer.acceptableContentTypes?.insert("text/plain")
        //发送网络请求
        AFN.POST(urlSting, parameters: parameters, success: { (_, result) -> Void in
            
            if let dict = result as? [String: AnyObject]{
                
                // 字典转模型
                let account = UserAccount(dict: dict)
                self.loadUserInfo(account, finished: finished)
            }
            }) { (_, error) -> Void in
                print(error)
        }
    }
    
    //MARK: 加载用户信息
    private func loadUserInfo(account: UserAccount,finished: (error: NSError?) -> ()){
        let urlString = "https://api.weibo.com/2/users/show.json"
        let parameters = ["access_token": account.access_token!,"uid" : account.uid!]
        let AFN = AFHTTPSessionManager()
        AFN.GET(urlString, parameters: parameters, success: { (_, result) -> Void in
            if let dict = result as? [String: AnyObject]{
                account.avatar_large = dict["avatar_large"] as? String
                account.name = dict["name"] as? String
                account.saveAccount()
                
                finished(error: nil)
            }
            }) { (_, error) -> Void in
                finished(error: error)
                print(error)
        }
    }
}
